import {pdfWorker} from '../../utils/ip'
const getPdfjsLib = (function () {
    let handle = null
    return function () {
        if (handle) return handle
        handle = import(/* webpackChunkName: "pdfjs-dist" */'pdfjs-dist').then(pdfjsLib => {
            // pdfjsLib.GlobalWorkerOptions.workerSrc = '/pdf/pdf.worker.min.js'
            pdfjsLib.GlobalWorkerOptions.workerSrc = pdfWorker()+'/pdf-worker.js'
            return pdfjsLib
        })

        return handle
    }
})()

// 应用全局PDF存储
const PDF_MAP = new Map()

const getPDFDocument = async function (src, reload = false) {
    if (PDF_MAP.get(src) && !reload) return PDF_MAP.get(src)
    const pdfjsLib = await getPdfjsLib()
    const pdfHandle = pdfjsLib.getDocument({
        url: src,
        cMapUrl: '/pdf/cmaps/',
      // cMapUrl: "https://cdn.jsdelivr.net/npm/pdfjs-dist@2.2.228/cmaps/",
        cMapPacked: true,
        rangeChunkSize: 256 * 1024, // 256kb
        disableStream: true,
        disableAutoFetch: true
    }).then(pdf => {
        return pdf
    })
    PDF_MAP.set(src, pdfHandle)
    return pdfHandle
}

export {
    getPDFDocument
}
